import React, {Component} from "react";
import {connect} from "react-redux";
import {isEqual} from "lodash";
import {Button, Form, Input, message, Modal, Popconfirm, Rate, Select, Table} from "antd";

import moment from "moment";

import {updateSingleRate} from "@/action";

import request, {get} from "@/axios/tools";

const DEFAULT_PAGE_SIZE = 20;
const DEFAULT_RATE_SIZE = 5;
const FORMAT_DATE = 'YYYY-MM-DD HH:mm';

const FormItem = Form.Item;
const {TextArea} = Input;
const {Option} = Select;
const mapStateToProps = state => {
    const {auth = {data: {}}} = state.httpData;
    const {singleRateState} = state;
    return {auth, singleRateState};
};

const mapDispatchToProps = (dispatch, ownProps) => {
    return {
        updateSingleRate: (...args) => dispatch(updateSingleRate(...args))
    }
}

// 添加服务评价
const AddRate = (props) => {
    const {form, form: {getFieldDecorator}, waiter: {id: waiterId, name}, requestWaiterData} = props;
    const formItemLayout = {
        labelCol: {span: 6},
        wrapperCol: {span: 14},
    };

    const postWaiterRate = (waiterID, parameter) => {
        request({
            url: '/restaurant/waiterEvaluate', method: 'post', params: {
                waiterID,
                type: 'ORDER',
                ...parameter
            }
        }).then((res) => {
            requestWaiterData();
            form.resetFields();
            // message.success('评价成功');
        }, (err) => {
            message.error('评价失败');
        })
    };

    const handleSubmitRate = () => {
        const values = form.getFieldsValue();
        values.score *= 20;
        values.restaurantScore *= 20;
        postWaiterRate(waiterId, values)
    }

    const {score, restaurantScore} = form.getFieldsValue();
    return (
        <div className="addRate-warpper">
            <Form>
                <FormItem
                    {...formItemLayout}
                    label={waiterId + '号服务员'}
                >
                    {name}
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="为服务员打分"
                >
                    {getFieldDecorator('score', {
                        rules: [{
                            required: true, message: '请选择服务评分!',
                        }]
                    })(
                        <Rate allowHalf/>
                    )}

                    {score && <span className="ant-rate-text">{score * 20} 分</span>}

                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="为餐厅打分"
                >
                    {getFieldDecorator('restaurantScore', {
                        rules: [{
                            required: true, message: '请选择服务评分!',
                        }]
                    })(
                        <Rate allowHalf/>
                    )}
                    {restaurantScore && <span className="ant-rate-text">{restaurantScore * 20} 分</span>}
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="您的宝贵意见"
                >
                    {getFieldDecorator('description', {
                        rules: []
                    })(
                        <TextArea rows={4}/>
                    )}
                </FormItem>
                <FormItem
                    wrapperCol={{span: 12, offset: 6}}
                >
                    <Button type="primary" onClick={handleSubmitRate}>提交</Button>
                </FormItem>
            </Form>
        </div>
    )
}

const WrapperAddRate = Form.create()(AddRate);


class WaiterSingleRate extends Component {
    constructor(props) {
        super(props);
        this.state = {
            data: [],
            total: 0,
            currentRatePage: 1,
            loading: false
        };
    }

    columns = [
        {
            title: 'ID',
            dataIndex: 'id',
        },
        {
            title: '服务评分',
            dataIndex: 'score',
        },
        {
            title: '餐馆评分',
            dataIndex: 'restaurantScore',
        },
        {
            title: '意见反馈',
            dataIndex: 'description',
        },
        {
            title: '评价时间',
            dataIndex: 'createTime',
            render: text => {
                return moment(text).format(FORMAT_DATE);
            }
        }
    ]

    requestRate(waiterID, page) {
        this.setState({loading: true})
        let {singleRateState, updateSingleRate, updateRateTable} = this.props;
        // let {currentRatePage: page} = this.state;
        updateRateTable(waiterID, page, () => {
            this.setState({loading: false});
        });
    }

    // requestRateByParent () {
    //   const {id} = this.props;
    //   const {currentRatePage: page} = this.state;
    //   this.requestRate(id, page);
    // }

    componentDidMount() {
        // console.log(this.props);
        const {id} = this.props;
        const {currentRatePage: page} = this.state;
        this.requestRate(id, page);
        // console.log(this.props);
    }

    render() {
        const {singleRateState, id} = this.props;
        const {[id]: rateData = {}} = singleRateState;
        const {data = [], total = 0} = rateData;
        return (
            <div className="rate-container">
                <Table rowKey="id" columns={this.columns} loading={this.state.loading} dataSource={data} size='middle'
                       pagination={
                           {
                               total: total,
                               defaultPageSize: DEFAULT_RATE_SIZE,
                               current: this.state.currentRatePage,
                               onChange: (current) => {
                                   const {id} = this.props;
                                   this.setState({currentRatePage: current});
                                   this.requestRate(id, current);
                               },
                               showTotal: (total) => {
                                   return `总共 ${total} 条评价`;
                               }
                           }
                       }
                />
            </div>
        )
    }

}

const WrapperSingleRate = connect(mapStateToProps, mapDispatchToProps)(WaiterSingleRate);


class SelectGender extends Component {
    constructor(props) {
        super(props);
        this.state = {
            DEF_GENDER: 'MALE'
        };
    }

    componentDidMount() {
        const {record, updateValue, waiterInfo} = this.props;
        if (!record || record && !record.gender) {
            const gender = waiterInfo && waiterInfo.gender || this.state.DEF_GENDER
            console.log(gender)
            updateValue('gender', gender);
        }
    }

    render() {
        const {updateValue, record = {}, waiterInfo} = this.props;
        const {gender} = record;
        const defValue = gender || waiterInfo.gender || this.state.DEF_GENDER;
        return (
            <Select value={defValue} style={{width: '100%'}} onChange={(value) => {
                updateValue('gender', value)
            }}>
                <Option value="MALE">男</Option>
                <Option value="FEMALE">女</Option>
            </Select>)
    }
}


class WaiterRate extends Component {
    constructor(props) {
        super(props);
        this.state = {
            restaurant: '',
            data: [],
            visible: false,
            rateVisible: false,
            loading: false,
            currentPage: 1,
            editId: '',
            cacheEdit: {},
            WAITER_FIELD: ['name', 'gender'],
            waiterInfo: {
                name: '',
                gender: ''
            },
            waiterRate: {
                name: '',
                waiterId: ''
            }
        };
    }

    columns = [
        {
            title: 'ID',
            dataIndex: 'id',
        },
        {
            title: '名字',
            dataIndex: 'name',
            width: 300,
            render: (text, record, index) => {
                return this.state.editId === index ?
                    <Input defaultValue={text} onChange={(e) => {
                        this.editChange(e.target.value, index, 'name')
                    }}/>
                    : text;
            }
        },
        {
            title: '性别',
            dataIndex: 'gender',
            width: 200,
            render: (text, record, index) => {
                return this.state.editId === index ?
                    <SelectGender record={record}
                                  updateValue={(field, value) => this.editChange(value, index, 'gender')}/>
                    : {'MALE': '男', 'FEMALE': '女'}[text + ''.toUpperCase()];
            }
        },
        {
            title: '总评分',
            dataIndex: 'totalScore',
        },
        {
            title: '平均分',
            dataIndex: 'avgScore',
        },
        {
            title: '评价次数',
            dataIndex: 'count',
            width: 200,
            render: (text, record, index) => {
                return this.state.editId === index ? (
                    <span>
            <span className="text-item">
              {text}
            </span>

                        {/* <Icon type="plus-square" style={{margin: '0 10px', fontSize: '16px'}}/> */}
          </span>
                ) : text;
            }
        },
        {
            title: '操作',
            width: 280,
            render: (text, record, index) => (
                <span>
          <Button className="plus-btn" type="dashed" icon="plus" onClick={() => this.handleAddRate(record)}>
            添加评价
          </Button>
          <span className="ant-divider"/>
                    {
                        this.state.editId === index ?
                            <span>
              <Button type="primary" onClick={() => this.waiterEditDone(index, 'save')}>保存</Button>
                <span className="ant-divider"/>
              <Button type="dashed" onClick={() => this.waiterEditDone(index, 'cancel')}>取消</Button>
            </span>
                            :
                            <span>
              <Button type="dashed" onClick={() => this.waiterEdit(index)}>编辑</Button>
               <span className="ant-divider"/>
              <Popconfirm title="确定删除?" onConfirm={() => {
                  this.deleteWaiter(record.id)
              }}>
                  <Button type="dashed">删除</Button>
              </Popconfirm>
            </span>
                    }
        </span>
            )
        },
    ];

    handleAddRate = (record) => {
        const {waiterRate} = this.state;
        if (waiterRate.id && waiterRate.id !== record.id) {
            let {addRateForm} = this.refs;
            if (addRateForm) addRateForm.resetFields();
        }
        this.setState({rateVisible: true, waiterRate: Object.assign({}, record)});
    }

    updateValue = (key, val) => {
        const {waiterInfo} = this.state;
        waiterInfo[key] = val;
        this.setState({
            ...waiterInfo
        });
    }

    editChange = (val, index, key) => {
        const {data, editId, cacheEdit} = this.state;
        data[index][key] = val;
        // console.log(data[index])
        this.setState({...data});
    }

    /**
     * 编辑服务员数据
     */
    waiterEdit = (index) => {
        const {data, editId, cacheEdit} = this.state;
        this.rollBackData();
        cacheEdit[index] = Object.assign({}, data[index]);
        this.setState({editId: index, ...cacheEdit, ...data});
    }

    rollBackData() {
        const {data, editId, cacheEdit} = this.state;
        if (!cacheEdit[editId]) return;
        data[editId] = cacheEdit[editId];
    }

    /**
     * 更新缓存数据
     * @param {*} type
     */
    updateCacheEdit = (type) => {
        const {data, cacheEdit, editId, waiterRate} = this.state;
        let fields = {
            'rate': ['totalScore', 'avgScore', 'count']
        };
        let filelsKey = fields[type];
        if (filelsKey) {
            let waiterData = data.filter((item) => {
                return item.id === waiterRate.id;
            })[0];
            // console.log(waiterData, cacheEdit, editId);
            if (waiterData && cacheEdit[editId]) {
                filelsKey.forEach((field) => {
                    cacheEdit[editId][field] = waiterData[field];
                });
            }
            this.setState({cacheEdit});
        }
    }

    updateSingleRate = () => {
        const {waiterRate: {id: waiterID}} = this.state;
        const {singleRateState,} = this.props;
        const {[waiterID]: rateData} = singleRateState;
        const page = rateData && rateData.page || 1;
        this.updateRateTable(waiterID, page);
    }

    updateRateTable(waiterID, page, endFn) {
        const {singleRateState, updateSingleRate} = this.props;
        get('/restaurant/listWaiterEvaluate', {
            waiterID,
            page,
            pageSize: DEFAULT_RATE_SIZE
        })
            .then((res) => {
                let rateData = {
                    ...singleRateState,
                    [waiterID]: {
                        data: res.data,
                        total: res.total
                    }
                }
                updateSingleRate(rateData);
                endFn && endFn();
                // console.log(this.props);
            }, (err) => {
                console.log(err);
            })
    }


    waiterEditDone = (index, type) => {
        const {data, editId, cacheEdit, waiterInfo, WAITER_FIELD} = this.state;
        if (type === 'cancel') {
            this.rollBackData();
            this.setState({editId: ''});
        } else if (type === 'save') {
            const {id, name} = data[index];
            const {name: cacheName} = cacheEdit[editId];

            console.log(cacheEdit[editId], data[index]);

            if (isEqual(cacheEdit[editId], data[index])) {
                return this.setState({editId: ''});
            }

            WAITER_FIELD.map((field) => {
                waiterInfo[field] = data[index][field];
            })

            this.setState({editId: '', ...waiterInfo});
            this.postWaiter({id});
        }
    }

    postWaiter({id = ''}) {
        const {restaurant, waiterInfo} = this.state;
        let paramter = {
            restaurantID: restaurant,
            ...waiterInfo
        };

        if (id) {
            paramter.id = id;
        }

        request({url: '/restaurant/waiter', method: 'post', params: paramter}).then((res) => {
            const {waiterInfo} = this.state;
            waiterInfo.name = '';
            waiterInfo.gender = 'MALE';
            this.setState({...waiterInfo, loading: false, visible: false});
            this.requestWaiterData();
        });
    }

    deleteWaiter(id) {
        request({url: '/restaurant/waiter/' + id}).then((res) => {
            this.requestWaiterData();
        });
    }

    requestWaiterData(restaurantID, page, endFn) {
        const {restaurant, currentPage} = this.state;
        restaurantID = restaurantID || restaurant;
        page = page || currentPage;

        get('/restaurant/listWaiter/', {
            restaurantID,
            page,
            pageSize: DEFAULT_PAGE_SIZE
        })
            .then(res => {
                const {data} = res;
                this.setState({data, total: res.total});
                endFn && endFn();
            })
    }

    componentDidMount() {
        let {auth: {data: {restaurant}}, updateSingleRate} = this.props;
        this.setState({restaurant});
        this.requestWaiterData(restaurant);
        updateSingleRate();
    }

    render() {
        console.log(this.state.total)
        return (
            <div className="content-container">
                <div className="opt-box">
                    <Button type="default" onClick={() => {
                        this.setState({visible: true});
                    }}>添加服务员</Button>
                </div>
                <Table ref="rateTable" rowKey="id" columns={this.columns} dataSource={this.state.data} size='middle'
                       pagination={
                           {
                               total: this.state.total,
                               size: 'lg',
                               defaultPageSize: DEFAULT_PAGE_SIZE,
                               current: this.state.currentPage,
                               onChange: (current) => {
                                   this.setState({currentPage: current});
                                   this.requestWaiterData('', current);
                               }
                           }
                       }
                       expandedRowRender={(props) => <WrapperSingleRate ref="waiterSingleRate" {...props}
                                                                        updateRateTable={(...args) => {
                                                                            this.updateRateTable(...args)
                                                                        }}/>}
                       onExpand={(expanded, record) => {
                       }}
                />
                <Modal
                    title="添加服务员"
                    visible={this.state.visible}
                    onOk={e => {
                        this.setState({visible: false});
                    }}
                    onCancel={e => {
                        this.setState({visible: false});
                    }}
                    footer={null}
                >
                    <div className="update-waiter">
                        <Input placeholder='请输入名称' value={this.state.waiterInfo.name} onChange={e => {
                            this.updateValue('name', e.target.value)
                            {/* this.setState({name: e.target.value}); */
                            }
                        }}/>
                        <div style={{marginTop: '15px'}}></div>
                        <SelectGender updateValue={this.updateValue} waiterInfo={this.state.waiterInfo}/>
                        <div style={{marginTop: '15px'}}></div>
                        <Button key="submit" type="primary" size="large" loading={this.state.loading} onClick={e => {
                            this.setState({loading: true});
                            this.postWaiter({id: ''});
                        }}>
                            保存
                        </Button>
                    </div>
                </Modal>
                <Modal title="添加服务评价"
                       visible={this.state.rateVisible}
                       onOk={e => {
                           this.setState({rateVisible: false});
                       }}
                       onCancel={e => {
                           this.setState({rateVisible: false});
                       }}
                       footer={null}>
                    <WrapperAddRate ref="addRateForm" waiter={this.state.waiterRate} requestWaiterData={() => {
                        this.requestWaiterData('', '', () => {
                            this.setState({rateVisible: false});
                            this.updateCacheEdit('rate');
                            this.updateSingleRate();
                        });
                    }}/>
                </Modal>
            </div>
        )
    }
}


export default connect(mapStateToProps, mapDispatchToProps)(WaiterRate);